package com.turbo.cloud.contract.web.logic;

import cn.hutool.core.util.StrUtil;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.PdfReader;
import com.turbo.cloud.contract.config.FilePathConfig;
import com.turbo.cloud.contract.constants.ContractConstants;
import com.turbo.cloud.contract.web.client.MinioFileClient;
import com.turbo.cloud.contract.web.entity.CtContractTemplate;
import com.turbo.cloud.contract.web.entity.CtContractTemplateForm;
import com.turbo.cloud.contract.web.exception.FormAlertEnum;
import com.turbo.cloud.contract.web.model.form.CtContractTemplateFormQO;
import com.turbo.cloud.contract.web.model.form.CtContractTemplateFormDO;
import com.turbo.cloud.contract.web.model.form.CtContractTemplateFormVO;
import com.turbo.cloud.contract.web.service.CtContractTemplateFormService;
import com.turbo.cloud.contract.web.service.CtContractTemplateService;
import com.turbo.cloud.core.api.Result;
import com.turbo.cloud.core.exception.BusinessException;
import com.turbo.cloud.core.utils.FileDownloadUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 合同模板表单 逻辑处理类
 * </p>
 *
 * @author zhangluning
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class FormLogic {
    final FilePathConfig filePathConfig;

    final CtContractTemplateFormService ctContractTemplateFormService;
    final CtContractTemplateService ctContractTemplateService;

    final MinioFileClient minioFileClient;

    /**
     * 查询合同模板表单列表
     *
     * @param ctContractTemplateFormQO 查询表单条件
     * @return Page
     */
    public List<CtContractTemplateFormVO> queryFormListByContractTemplateId(CtContractTemplateFormQO ctContractTemplateFormQO) {
        /*
         * 查询合同模板
         */
        CtContractTemplate ctContractTemplate = ctContractTemplateService.getById(ctContractTemplateFormQO.getContractTemplateId());
        if (Objects.isNull(ctContractTemplate)) {
            throw new BusinessException(FormAlertEnum.FORM0001_合同模板不存在);
        }
        /*
         * 拿到合同模板里面的文件ID下载到服务器本地，解读出PDF的表单
         */

        Result<String> result = minioFileClient.getFileUrl(ctContractTemplate.getFileId(), ContractConstants.MINIO_BUCKET_NAME);
        String fileUrl = result.getResult();

        if (StrUtil.isBlank(fileUrl)) {
            throw new BusinessException(FormAlertEnum.FORM0002_合同模板文件不存在);
        }

        String pdfFilePath = filePathConfig.getDownloadPathOfYMD();
        boolean isDownload = FileDownloadUtil.downloadToServer(fileUrl, pdfFilePath, ctContractTemplate.getFileId());
        if (!isDownload) {
            throw new BusinessException(FormAlertEnum.FORM0003_合同模板文件下载失败);
        }

        List<CtContractTemplateFormVO> ctContractTemplateFormVOList = new ArrayList<>();

        try {
            String pdfFileFullPath = filePathConfig.getDownloadPathOfYMD() + ctContractTemplate.getFileId();
            PdfReader reader = new PdfReader(pdfFileFullPath);
            AcroFields fields = reader.getAcroFields();

            Map<String, AcroFields.Item> map = fields.getFields();
            for (Map.Entry<String, AcroFields.Item> entry : map.entrySet()) {
                String key = entry.getKey();
                AcroFields.Item item = entry.getValue();
                // 在这里你可以对 key 和 item 进行操作
                System.out.println("Key: " + key);
                System.out.println("Value: " + item);

                CtContractTemplateFormVO ctContractTemplateFormVO = new CtContractTemplateFormVO();
                ctContractTemplateFormVO.setFormCode(key);
                //ctContractTemplateFormVO.setFormName(item.getValue(0).)
            }

        } catch (IOException e) {
            throw new BusinessException(FormAlertEnum.FORM0004_合同模板文件PDF解析失败);
        }

        return ctContractTemplateFormVOList;
    }

    /**
     * 新增合同模板表单
     *
     * @param ctContractTemplateFormDO 实体
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean createContractTemplateForm(CtContractTemplateFormDO ctContractTemplateFormDO) {
        CtContractTemplateForm ctContractTemplateForm = new CtContractTemplateForm();
        BeanUtils.copyProperties(ctContractTemplateFormDO, ctContractTemplateForm);

        boolean roleSaveResult = ctContractTemplateFormService.save(ctContractTemplateForm);
        if (!roleSaveResult) {
            throw new BusinessException("新增合同模板表单失败");
        }
        return true;
    }

    /**
     * 修改合同模板表单
     *
     * @param ctContractTemplateFormDO 实体
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean modifyContractTemplateForm(CtContractTemplateFormDO ctContractTemplateFormDO) {
        CtContractTemplateForm ctContractTemplateForm = new CtContractTemplateForm();
        BeanUtils.copyProperties(ctContractTemplateFormDO, ctContractTemplateForm);

        boolean result = ctContractTemplateFormService.updateById(ctContractTemplateForm);
        if (!result) {
            throw new BusinessException("修改合同模板表单失败");
        }

        return true;
    }
}
